package com.springcloud.tools.interceptor;

import com.springcloud.tools.annotation.AutoIdempotent;
import com.springcloud.tools.exception.IdempotentException;
import com.springcloud.tools.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author fuc
 * @create 2020-08-19
 */
@Component
public class IdempotentInterceptor implements HandlerInterceptor {

  @Autowired TokenService tokenService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    if (Objects.equals(handler instanceof HandlerMethod, false)) {
      return true;
    }
    Method method = ((HandlerMethod) handler).getMethod();
    AutoIdempotent autoIdempotent = method.getAnnotation(AutoIdempotent.class);
    if (Objects.nonNull(autoIdempotent)) {
      try {
        return tokenService.checkToken(request);
      } catch (IdempotentException e) {
        throw e;
      }
    }
    return true;
  }
}
